#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

using namespace std;

int main()
{
    int listensock = socket(AF_INET, SOCK_STREAM, 0);
    if (listensock < 0)
    {
        cout << "create socket error" << endl;
        return 0;
    }

    struct sockaddr_in local;
    memset(&local, 0, sizeof local);
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = htonl(INADDR_ANY);
    local.sin_port = htons(8080);

    if (bind(listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
    {
        cout << "bind error" << endl;
        exit(-1);
    }

    if (listen(listensock, 10) < 0)
    {
        cout << "listen error" << endl;
        exit(-1);
    }

    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    int servicesock = accept(listensock, (struct sockaddr *)&listensock, &client_addr_len);
    if (servicesock < 0)
    {
        cout << "Accept error" << endl;
        exit(-1);
    }

    cout << "Client connected!" << endl;

    // HTML content to send
    const char *html_content =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/html; charset=UTF-8\r\n"
        "\r\n"
        "<html>\r\n"
        "<head><title>Simple HTML Page</title></head>\r\n"
        "<body>\r\n"
        "<h1>Hello, World!</h1>\r\n"
        "<p>This is a simple HTML page served by a C++ server.</p>\r\n"
        "</body>\r\n"
        "</html>\r\n";

    // Send HTML content
    ssize_t bytes_sent = send(servicesock, html_content, strlen(html_content), 0);
    if (bytes_sent < 0)
    {
        perror("Send error");
        close(servicesock);
        close(listensock);
        return 1;
    }

    cout << "HTML content sent to client." << endl;

    // Close sockets
    close(servicesock);
    close(listensock);

    return 0;
}